﻿CREATE PROCEDURE [dbo].[InterpolateFloatData]
	@startIdExclusive bigint,
	@endIdInclusive bigint = null
AS
BEGIN
	DECLARE @minT DATETIME, @maxT DATETIME
	DECLARE @maxId BIGINT

	SELECT @minT= min(Time) FROM FloatData WHERE DataId > @startIdExclusive
	if @endIdInclusive IS NULL 
	BEGIN
		SELECT @maxt= max(time) FROM floatdata
		SELECT @maxId = max(dataId) FROM FloatData
	END
	ELSE
	BEGIN
		SELECT @maxT= max(Time) FROM FloatData WHERE DataId <= @endIdInclusive
		SELECT @maxId = @endIdInclusive
	END
	PRINT @maxT

	SELECT @minT = dateadd(minute, datediff(minute,0,@minT) / 15 * 15, 0)
	SELECT @maxT = dateadd(minute, datediff(minute,0,@maxT) / 15 * 15, 0)

	PRINT @minT
	PRINT @maxT

	;WITH timeInt (time) AS
	(
		SELECT cast(@minT AS DATETIME2)
		UNION  ALL
		SELECT dateadd(minute, 15, time) FROM timeInt
		WHERE time < @maxT
	), data (tagId, prev, preval, time, val) as
	(
		SELECT 
			tagId,
			prev = lag(time,1) over (partition by tagId order by time),
			preval = lag(value,1) over (partition by tagId order by time),
			time,
			val = value
		FROM 
			FloatData
			WHERE 
				DataId > @startIdExclusive AND
				DataId <= @maxId
	)
	SELECT 
		[Time] = [dbo].[Get15MinuteTime](timeInt.time),
		[TagId] = tagId,
		[Value] = CASE WHEN d.preVal IS NULL OR d.val IS NULL OR d.prev IS NULL  OR d.time IS NULL THEN NULL ELSE
			d.preval + datediff(ms, timeInt.time, d.prev) * (d.val - d.preval)/datediff(ms, d.time, d.prev)
		END,
		[IsNan] = 0,
		[IsInfinity] = 0
	FROM timeInt
	INNER JOIN data d on
		d.prev < timeInt.time AND
		d.time >= timeInt.time
	OPTION (maxrecursion 0)
END